<template>
  <div>

    <div style="overflow: hidden;width: 1800px">
      <!--  根据预约状态进行条件查询  -->
      <div style="float: right;">
        <el-select v-model="stateQuery.value" placeholder="根据预约状态查询" @change="handleSelectChange">
          <el-option
              v-for="item in stateQuery"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </div>
      <!--  数据展示部分  -->
      <!--分页组件-->
      <div class="page" style="float: left">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="this.paging.total">
        </el-pagination>
      </div>
      <!--列表组件-->
      <div class="list">
        <el-table
            stripe border
            ref="multipleTable"
            :data="recordList"
            tooltip-effect="dark"
            style="width: 100%; font-weight: bold"
            :header-cell-style="{background:'#E4E7ED','text-align':'center',color:'#000',height:'25px',lineHeight:'25px'}">
          <!--        <el-table-column type="selection" width="55"></el-table-column>-->
          <el-table-column v-if="false" label="编号" prop="id"></el-table-column>
          <el-table-column label="患者" prop="patient.name"></el-table-column>
          <el-table-column label="预约发起时间" prop="createTime"></el-table-column>
          <el-table-column label="医生" prop="docker.name"></el-table-column>
          <el-table-column label="科室" prop="department.name"></el-table-column>
          <el-table-column label="挂号类型" prop="registrationType.typeName"></el-table-column>
          <el-table-column label="预约日期" prop="date"></el-table-column>
          <el-table-column label="预约时间段">
            <template slot-scope="scope">
              {{ scope.row.timePeriod.startTime }} - {{ scope.row.timePeriod.endTime }}
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="money"></el-table-column>
          <el-table-column label="状态" prop="state" :formatter="formatState"></el-table-column>
          <el-table-column v-if="false" label="订单号" prop="tradeNo"></el-table-column>
          <el-table-column v-if="false" label="支付状态" prop="payType"></el-table-column>
          <el-table-column label="操作">
            <!-- 根据预约状态不同显示不同的操作按钮  -->
            <template slot-scope="scope">
              <el-button v-if="scope.row.state === 0" type="danger" size="small"
                         @click="toCancel(scope.row)">取消
              </el-button>
              <el-button v-else-if="scope.row.state === 1" type="primary" size="small"
                         @click="toEvaluate(scope.row.docker)">评价
              </el-button>
              <el-button v-if="scope.row.state === 1 || scope.row.state === 2" type="info" size="small"
                         @click="toDelete(scope.row.id)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--    弹窗组件-->
    <div>
      <el-dialog title="评价医生" :visible.sync="dialogFormVisible"
                 :lock-scroll="true"
                 :close-on-click-modal="false"
                 width="500px">
        <!--  头像-->
        <el-row class="demo-avatar demo-basic" style="text-align: center">
          <el-col :span="24">
            <el-avatar :size="50" :src="docker.img"></el-avatar>
          </el-col>
          <span style="margin: 0 5px 0 0;">
            {{ departName }}
            &nbsp;&nbsp;
            {{ docker.name }}
          </span>
        </el-row>
        <!--医生信息-->
        <div style=" margin: 10px 0">
          <el-tag type="success"> {{ docker.introduce }}</el-tag>
          &nbsp;&nbsp;
          <el-tag type="warning"> {{ docker.proficientIn }}</el-tag>
        </div>
        <!--评分组件-->
        <div>
          <div style="margin: 10px 0;display: inline">
            <span style="float: left;margin: 0 5px 0 0">
              评分:
            </span>
            <el-rate
                v-model="commentObj.score"
                :colors="commentObj.colors">
            </el-rate>
          </div>
          <div style="margin: 10px 0;">
            <el-input
                type="textarea"
                autosize
                placeholder="请输入评价"
                v-model="commentObj.comment">
            </el-input>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="toCancelForWindow">取消</el-button>
          <el-button type="primary" @click="toConfirmForWindow">确认</el-button>
        </div>
      </el-dialog>
    </div>

    <div>
      <button @click="toAppointments">
        <a target="_blank">点击预约</a>
      </button>
      <button @click="refreshPage">刷新整个页面</button>
    </div>
  </div>
</template>

<script>
import {defineComponent} from 'vue'
import MainHeader from "@/views/MainHeader.vue";


export default defineComponent({
  name: "Appointment",
  components: {MainHeader},
  data() {
    return {
      //预约记录对象
      record: {},
      //预约记录列表对象
      recordList: [],
      //评价对象
      comment: {},
      //评分评价对象
      commentObj: {
        score: 5,
        comment: '',
        colors: ['#99A9BF', '#F7BA2A', '#FF9900']
      },
      //状态查询对象
      stateQuery: [
        {value: null, label: '全部'},
        {value: 0, label: '等待中'},
        {value: 1, label: '已完成'},
        {value: 2, label: '已取消'},
      ],
      //分页对象
      paging: {
        current: 1,
        size: 5,
        total: 0
      },
      //医生对象
      docker: {},
      //科室名称
      departName: '',
      //对话框显示
      dialogFormVisible: false,
      currentPage: 1,
      alipayForm: '',
    }

  },
  mounted() {
    this.getRecordList()
    this.getRecordTotal()
  },
  methods: {
    //得到预约列表
    getRecordList() {
      this.$http.get('/convention/page', {
        params: {
          current: this.paging.current,
          size: this.paging.size,
          userId: null,
          state: this.stateQuery.value
        }
      })
          .then(res => {
            if (res.status === 200) {
              this.recordList = res.data.records
              console.log(res.data.records);
            }
          }).catch(err => {
        this.$message.error('数据请求异常，请稍后重试')
      });
    },
    //下拉框改变事件
    handleSelectChange(value) {
      this.getRecordList()
      this.getRecordTotal()

    },
    //删除按钮点击事件
    toDelete(id) {
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/convention/delete/" + id)
            .then(res => {
              if (res.data) {
                this.getRecordList()
              }
            })
        this.$message.success('已删除成功');
      }).catch(() => {
        this.$message.warning('已取消删除');
      });
    },
    //取消按钮点击事件
    toCancel(row) {
      console.log(row);
      // 获取当前日期，并格式化为 YYYY-MM-DD 的格式
      const currentDate = new Date().toISOString().split('T')[0];
      // 假设表中相关字段存储在 this.recordDate 中
      if (currentDate === row.date) {
        // 如果当前日期与表中相关字段相同，则禁止取消操作
        this.$message.warning('赴约当天不允许取消预约哟');
      } else {
        this.$confirm('此操作将取消预约, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (row.payType === 0) {
            this.$message.error('由于技术原因，暂不支持微信退款,请见谅')
          } else {
            this.$http.post("/alipay/refund", row)
                .then(res => {
                  console.log(res);
                  if (res.data === 200) {
                    this.getRecordList()
                    this.$message.success('取消预约成功，请留意退款到账')
                  } else {
                    this.getRecordList()
                    this.$message.error('取消预约失败，请稍后重试')
                  }
                })
          }
        }).catch(() => {
          this.$message.warning('已撤销取消,请按时赴约');
        });
      }
    },
    //根据状态码显示不同的预约状态
    formatState(row) {
      switch (row.state) {
        case 0:
          return '等待中';
        case 1:
          return '已完成';
        case 2:
          return '已取消';
        default:
          return '';
      }
    },
    //评价按钮点击事件-
    toEvaluate(docker) {
//得到医生信息
      this.docker = docker
      this.departName = this.docker.department.name
//打开评价对话框
      this.dialogFormVisible = true


    },
    //弹窗取消按钮点击事件
    toCancelForWindow() {
      this.commentObj.comment = ''
      this.dialogFormVisible = false
    },
    //弹窗确认按钮点击事件
    toConfirmForWindow() {
      this.comment = {
// userId: this.record.userId,
        userId: 1,
        dockerId: this.docker.id,
        score: this.commentObj.score,
        comment: this.commentObj.comment,
      }
      this.$http.post('/comment/save', this.comment)
          .then(res => {
            if (res.data) {
              this.$message.success('评价成功')
            }
          })
          .catch(err => {
            this.$message.error('服务器异常,评价失败')
          })
          .finally(() => {
            this.toCancelForWindow()
          })
    },
    //获得预约列表总条数
    getRecordTotal() {
      this.$http.get('/convention/count', {
        params: {
          userId: null,
          state: this.stateQuery.value
        }
      })
          .then(res => {
            if (res.status === 200) {
              this.paging.total = res.data.data
            }
          }).catch(err => {
        this.$message.error('数据请求异常，请稍后重试')
      })
    },
    //每页条数改变方法
    handleSizeChange(size) {
      this.paging.size = size
      this.getRecordList()
    },
    //页码改变事件
    handleCurrentChange(current) {
      this.paging.current = current
      this.getRecordList()
    },

    //支付宝支付测试方法
    toAppointments() {
      let convention = {
        id: 1,
        userId: 1,
        departmentId: 1,
        docId: 1,
        patId: 1,
        typeId: 1,
        money: 1,
        date: "2023-03-03 00:00:00",
        timeId: 1,
        state: '',
        tradeNo: "",
        payType: 1
      };
      this.$http.post('/alipay/pay', convention).then(resp => {
        // 添加之前先删除一下，如果单页面，页面不刷新，添加进去的内容会一直保留在页面中，二次调用form表单会出错
        const divForm = document.getElementsByTagName('div')
        if (divForm.length) {
          document.body.removeChild(divForm[0])
        }
        const div = document.createElement('div')
        div.innerHTML = resp.data // data就是接口返回的form 表单字符串
        document.body.appendChild(div)
        document.forms[0].setAttribute('target', '_blank') // 新开窗口跳转
        document.forms[0].submit()
        //跳转支付页面后，重新加载本页面
        this.$router.go(0);
      })
    },
    //支付宝查询支付状态测试方法
    checkOrder(tradeNo) {
      let convention = {
        id: 1,
        userId: 1,
        departmentId: 1,
        docId: 1,
        patId: 1,
        typeId: 1,
        money: 1,
        date: "",
        timeId: 1,
        state: 0,
        traceNo: 98052310
      };
      let count = 0;
      let timer = window.setInterval(() => {
        this.$http.get("/alipay/queryPay?alipayTraceNo=" + tradeNo)
            .then(res => {
              console.log("queryPay", res.data)
              //如果是成功，就关闭支付窗体，停止定时器
              if (res.data.code === "10000") {
                this.$message.success("支付成功")
                window.clearInterval(timer);
              }
            })
        count++;
        if (count === 20) {
          this.$http.post("/alipay/cancelPay", convention)
              .then(res => {
                console.log("cancelPay", res.data)
                //如果是成功，就关闭支付窗体，停止定时器
                // if (res.data === "SUCCESS") {
                //   this.$message.success("支付成功")
                //   window.clearInterval(timer);
                // }
              })
          this.$message.error("支付超时")
          window.clearInterval(timer);
        }
      }, 2000);
    },
    //支付宝退款测试方法
    toRefund() {
      let convention = {
        id: 1,
        userId: 1,
        departmentId: 1,
        docId: 1,
        patId: 1,
        typeId: 1,
        money: 1,
        date: "",
        timeId: 1,
        state: 0,
        traceNo: 98052310
      };
      this.$http.post('/alipay/refund', convention)
          .then(res => {
            console.log(res);
            if (res.status === 200) {
              this.$message.success('取消预约成功，请留意退款到账')
            }
          }).catch(err => {
        this.$message.error('数据请求异常，请稍后重试')
      })
    },

    // 重新加载当前页面
    refreshPage() {
      this.$router.go(0);
    }

  }

})

</script>

<style>

</style>
